package com.dengpp.pdform;


import android.Manifest;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.dengpp.pdform.adapter.AttributeAdapter;
import com.dengpp.pdform.config.AttributeConfig;
import com.dengpp.pdform.config.FormConfig;
import com.dengpp.pdform.model.LocationInfo;
import com.dengpp.pdform.model.MediaFile;
import com.dengpp.pdform.model.MediaFileDialog;
import com.dengpp.pdform.view.CameraXActivity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AttributeFormActivity extends AppCompatActivity {

    private static final String EXTRA_FORM_CONFIG = "form_config";
    private static final int REQUEST_MEDIA_PICKER = 1001;
    private static final int REQUEST_CAMERA = 1002;
    private static final int REQUEST_PERMISSION_CAMERA = 1003;
    private static final int REQUEST_PERMISSION_STORAGE = 1004;
    private static final int REQUEST_PERMISSION_LOCATION = 1006;
    private static final int REQUEST_CUSTOM_CAMERA = 1007;
    private static final int REQUEST_CAMERA_X = 1008;
    private static final String TAG = "AttributeFormActivity";

    // 权限数组
    private static final String[] CAMERA_PERMISSIONS = {
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    private static final String[] STORAGE_PERMISSIONS = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    private static final String[] LOCATION_PERMISSIONS = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
    };

    // 当前请求的操作类型
    private String currentAction = ""; // "gallery", "camera", "video"

    private RecyclerView recyclerView;
    private AttributeAdapter adapter;
    private FormConfig formConfig;
    private String currentMediaKey;
    private Uri cameraImageUri;
    private LocationInfo currentLocationInfo;

//    public static void start(Activity activity, FormConfig formConfig, int requestCode) {
//        Intent intent = new Intent(activity, AttributeFormActivity.class);
//        intent.putExtra(EXTRA_FORM_CONFIG, formConfig);
//        activity.startActivityForResult(intent, requestCode);
//    }


    // 添加自定义视图注册表
    private static final Map<String, Class<?>> customViewRegistry = new HashMap<>();

    /**
     * 注册自定义视图类
     */
    public static void registerCustomView(String key, Class<?> viewClass) {
        customViewRegistry.put(key, viewClass);
    }

    /**
     * 获取已注册的自定义视图类
     */
    public static Class<?> getCustomViewClass(String key) {
        return customViewRegistry.get(key);
    }

    /**
     * 启动方法 - 预处理自定义视图
     */
    public static void start(Activity activity, FormConfig formConfig, int requestCode) {
        // 在启动前预处理自定义视图
        preprocessCustomViews(formConfig);

        Intent intent = new Intent(activity, AttributeFormActivity.class);
        intent.putExtra(EXTRA_FORM_CONFIG, formConfig);
        activity.startActivityForResult(intent, requestCode);
    }

    /**
     * 预处理自定义视图，将 Class 对象注册到注册表
     */
    private static void preprocessCustomViews(FormConfig formConfig) {
        for (AttributeConfig attribute : formConfig.getAttributes()) {
            if (attribute.getType() == AttributeConfig.AttributeType.CUSTOM_VIEW &&
                    attribute.getCustomViewClass() != null) {

                String classKey = attribute.getCustomViewClassKey();
                if (classKey != null) {
                    // 注册自定义视图类
                    registerCustomView(classKey, attribute.getCustomViewClass());
                }
            }
        }
    }

    /**
     * 恢复自定义视图类引用
     */
    private void restoreCustomViewClasses() {
        for (AttributeConfig attribute : formConfig.getAttributes()) {
            if (attribute.getType() == AttributeConfig.AttributeType.CUSTOM_VIEW) {
                String classKey = attribute.getCustomViewClassKey();
                if (classKey != null) {
                    Class<?> viewClass = getCustomViewClass(classKey);
                    if (viewClass != null) {
                        // 使用反射设置自定义视图类
                        try {
                            java.lang.reflect.Field field = AttributeConfig.class.getDeclaredField("customViewClass");
                            field.setAccessible(true);
                            field.set(attribute, viewClass);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_attribute_form);

        initData();
        initViews();
        setupRecyclerView();
    }

    private void initData() {
        if (getIntent() != null && getIntent().hasExtra(EXTRA_FORM_CONFIG)) {
            formConfig = (FormConfig) getIntent().getSerializableExtra(EXTRA_FORM_CONFIG);

            // 在反序列化后恢复数据
            if (formConfig != null) {
                formConfig.restoreAfterSerialization();

                // 恢复自定义视图类引用
                restoreCustomViewClasses();
            }
        }

        if (formConfig == null) {
            Toast.makeText(this, "表单配置错误", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void initViews() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(formConfig.getTitle());
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        Button btnSubmit = findViewById(R.id.btn_submit);
        Button btnCancel = findViewById(R.id.btn_cancel);

        btnSubmit.setText(formConfig.getSubmitButtonText());
        btnCancel.setText(formConfig.getCancelButtonText());

        btnSubmit.setOnClickListener(v -> submitForm());
        btnCancel.setOnClickListener(v -> cancelForm());

        // 如果不是编辑模式，隐藏按钮
        if (!formConfig.isEditMode()) {
            btnSubmit.setVisibility(View.GONE);
            btnCancel.setText("关闭");
        }
    }

    private void setupRecyclerView() {
        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        adapter = new AttributeAdapter(formConfig.getAttributes(), formConfig.isEditMode(),
                new AttributeAdapter.OnAttributeChangeListener() {
                    @Override
                    public void onAttributeChanged(String key, Object value) {
                        updateAttributeValue(key, value);
                    }

                    @Override
                    public void onMediaAddRequested(String key, MediaFileDialog mediaFileDialog) {
                        currentMediaKey = key;
                        if (mediaFileDialog == null) {
                            mediaFileDialog = new MediaFileDialog();
                        }
                        showMediaSelectionDialog(mediaFileDialog);
                    }

                    @Override
                    public void onMediaRemoveRequested(String key, int position) {
                        removeMediaFile(key, position);
                    }
                });

        recyclerView.setAdapter(adapter);
    }

    private void updateAttributeValue(String key, Object value) {
        Log.d(TAG, "更新属性: " + key + " = " + value);
        for (AttributeConfig attribute : formConfig.getAttributes()) {
            if (attribute.getKey().equals(key)) {
                attribute.setValue(value);
                break;
            }
        }
    }

    private void showMediaSelectionDialog(MediaFileDialog mediaFileDialog) {
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(this);
        builder.setTitle(mediaFileDialog.getTitle() == null ? "选择媒体来源" : mediaFileDialog.getTitle());
        String[] strings = {"从相册选择", "拍照（系统相机）", "录制视频（系统相机）", "拍照(系统相机-记录位置)", "CameraX相机(推荐)"};
        builder.setItems(mediaFileDialog.getItems().length == 0 ? strings : mediaFileDialog.getItems(), (dialog, which) -> {
            //都给使用getItems来判断，避免出现一个有值一个没有的情况
            if (mediaFileDialog.getItems().length > 0) {
                String s = null;
                try {
                    //异常处理，避免使用者参数传入错误的情况
                    s = mediaFileDialog.getCurrentAction()[which];
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(this, "弹框参数传递错误", Toast.LENGTH_LONG).show();
                }
                if ("gallery".equalsIgnoreCase(s)) {
                    currentAction = "gallery";
                    if (checkStoragePermissions()) {
                        openGallery();
                    }
                } else if ("camera".equalsIgnoreCase(s)) {
                    currentAction = "camera";
                    if (checkCameraPermissions()) {
                        openCamera();
                    }
                } else if ("video".equalsIgnoreCase(s)) {
                    currentAction = "video";
                    if (checkCameraPermissions()) {
                        openVideoRecorder();
                    }
                } else if ("camera_with_location".equalsIgnoreCase(s)) {
                    currentAction = "camera_with_location";
                    if (checkCameraPermissions() && checkLocationPermissions()) {
                        openCameraWithLocation();
                    }
                } else if ("camerax".equalsIgnoreCase(s)) {
                    currentAction = "camerax";
                    if (checkCameraPermissions() && checkLocationPermissions()) {
                        openCameraX();
                    }
                }
            } else {
                switch (which) {
                    case 0: // 从相册选择
                        currentAction = "gallery";
                        if (checkStoragePermissions()) {
                            openGallery();
                        }
                        break;
                    case 1: // 拍照
                        currentAction = "camera";
                        if (checkCameraPermissions()) {
                            openCamera();
                        }
                        break;
                    case 2: // 录制视频
                        currentAction = "video";
                        if (checkCameraPermissions()) {
                            openVideoRecorder();
                        }
                        break;
                    case 3: // 拍照(记录位置，点击拍照的时候记录当前位置)
                        currentAction = "camera_with_location";
                        if (checkCameraPermissions() && checkLocationPermissions()) {
                            openCameraWithLocation();
                        }
                        break;
                    case 4: // 自定义相机(记录位置)
                        // CameraX相机
                        currentAction = "camerax";
                        if (checkCameraPermissions() && checkLocationPermissions()) {
                            openCameraX();
                        }
                        break;
                }
            }


        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    /**
     * 检查位置权限
     */
    private boolean checkLocationPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                    checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
                    showPermissionExplanationDialog("位置权限", "需要位置权限来记录拍照时的地理位置",
                            REQUEST_PERMISSION_LOCATION);
                } else {
                    requestPermissions(LOCATION_PERMISSIONS, REQUEST_PERMISSION_LOCATION);
                }
                return false;
            }
        }
        return true;
    }

    /**
     * 检查存储权限
     */
    private boolean checkStoragePermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                    checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

                // 解释为什么需要权限
                if (shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    showPermissionExplanationDialog("存储权限", "需要存储权限来访问您的相册和保存媒体文件",
                            REQUEST_PERMISSION_STORAGE);
                } else {
                    requestPermissions(STORAGE_PERMISSIONS, REQUEST_PERMISSION_STORAGE);
                }
                return false;
            }
        }
        return true;
    }

    /**
     * 检查相机权限
     */
    private boolean checkCameraPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            boolean hasCameraPermission = checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
            boolean hasStoragePermission = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;

            if (!hasCameraPermission || !hasStoragePermission) {
                List<String> permissionsToRequest = new ArrayList<>();

                if (!hasCameraPermission) {
                    permissionsToRequest.add(Manifest.permission.CAMERA);
                }
                if (!hasStoragePermission) {
                    permissionsToRequest.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                }

                // 解释为什么需要权限
                if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA) ||
                        shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

                    showPermissionExplanationDialog("相机和存储权限", "需要相机权限来拍照/录像，需要存储权限来保存媒体文件",
                            REQUEST_PERMISSION_CAMERA);
                } else {
                    requestPermissions(permissionsToRequest.toArray(new String[0]), REQUEST_PERMISSION_CAMERA);
                }
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            case REQUEST_PERMISSION_STORAGE:
                handleStoragePermissionResult(grantResults);
                break;
            case REQUEST_PERMISSION_CAMERA:
                handleCameraPermissionResult(grantResults);
                break;
            case REQUEST_PERMISSION_LOCATION:
                handleLocationPermissionResult(grantResults);
                break;
        }
    }

    /**
     * 处理存储权限请求结果
     */
    private void handleStoragePermissionResult(int[] grantResults) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // 权限已授予，执行相应操作
            switch (currentAction) {
                case "gallery":
                    openGallery();
                    break;
            }
        } else {
            // 权限被拒绝
            Toast.makeText(this, "存储权限被拒绝，无法访问相册", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 处理位置权限请求结果
     */
    private void handleLocationPermissionResult(int[] grantResults) {
        boolean allGranted = true;
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                allGranted = false;
                break;
            }
        }

        if (allGranted) {
            // 权限已授予，执行相应操作
            switch (currentAction) {
                case "camera_with_location":
                    openCameraWithLocation();
                    break;
            }
        } else {
            Toast.makeText(this, "位置权限被拒绝，无法记录地理位置", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 处理相机权限请求结果
     */
    private void handleCameraPermissionResult(int[] grantResults) {
        boolean allGranted = true;
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                allGranted = false;
                break;
            }
        }

        if (allGranted) {
            // 所有权限都已授予，执行相应操作
            switch (currentAction) {
                case "camera":
                    openCamera();
                    break;
                case "video":
                    openVideoRecorder();
                    break;
            }
        } else {
            // 权限被拒绝
            Toast.makeText(this, "相机或存储权限被拒绝，无法使用拍照/录像功能", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 显示权限解释对话框
     */
    private void showPermissionExplanationDialog(String title, String message, final int requestCode) {
        new androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton("确定", (dialog, which) -> {
                    if (requestCode == REQUEST_PERMISSION_STORAGE) {
                        requestPermissions(STORAGE_PERMISSIONS, REQUEST_PERMISSION_STORAGE);
                    } else {
                        requestPermissions(CAMERA_PERMISSIONS, REQUEST_PERMISSION_CAMERA);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void openGallery() {
        try {
            // 再次确认权限（双重检查）
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "存储权限未授予", Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.putExtra(Intent.EXTRA_MIME_TYPES, new String[]{"image/*", "video/*"});
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            startActivityForResult(Intent.createChooser(intent, "选择媒体文件"), REQUEST_MEDIA_PICKER);
        } catch (Exception e) {
            Log.e(TAG, "打开相册失败", e);
            Toast.makeText(this, "无法打开相册", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 打开 CameraX 相机
     */
    private void openCameraX() {
        try {
            CameraXActivity.start(this, REQUEST_CAMERA_X);
        } catch (Exception e) {
            Log.e(TAG, "打开 CameraX 相机失败", e);
            Toast.makeText(this, "无法打开相机", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 拍照并记录位置信息
     */
    private void openCameraWithLocation() {
        try {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            PackageManager packageManager = getPackageManager();

            try {
                String fileName = "IMG_" + System.currentTimeMillis() + ".jpg";
                cameraImageUri = createImageUri(fileName);

                if (cameraImageUri != null) {
                    // 获取当前位置
                    LocationInfo locationInfo = getCurrentLocation();

                    // 为所有可能的相机应用授予权限
                    List<ResolveInfo> resInfoList = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
                    for (ResolveInfo resolveInfo : resInfoList) {
                        String packageName = resolveInfo.activityInfo.packageName;
                        grantUriPermission(packageName, cameraImageUri,
                                Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    }

                    intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraImageUri);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

                    // 保存位置信息到临时变量，在onActivityResult中使用
                    currentLocationInfo = locationInfo;

                }
                startActivityForResult(intent, REQUEST_CAMERA);
            } catch (Exception e) {
                showNoCameraAppDialog();
            }
        } catch (Exception e) {
            Log.e(TAG, "打开带位置相机失败", e);
            Toast.makeText(this, "无法打开相机: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 获取当前位置信息
     */
    private LocationInfo getCurrentLocation() {
        try {
            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

            // 检查位置服务是否启用
            if (locationManager != null && locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                // 等待位置更新
                Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (lastKnownLocation == null) {
                    lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                }

                if (lastKnownLocation != null) {
                    return new LocationInfo(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
                }
            }

            // 如果无法获取精确位置，返回默认位置或null
            return new LocationInfo(0, 0); // 默认位置
        } catch (SecurityException e) {
            Log.e(TAG, "位置权限异常", e);
            return null;
        } catch (Exception e) {
            Log.e(TAG, "获取位置失败", e);
            return null;
        }
    }

    private void openCamera() {
        try {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            // 检查是否有应用可以处理相机意图
            PackageManager packageManager = getPackageManager();

            try {
                String fileName = "IMG_" + System.currentTimeMillis() + ".jpg";
                cameraImageUri = createImageUri(fileName);

                if (cameraImageUri != null) {
                    // 为所有可能的相机应用授予权限
                    List<ResolveInfo> resInfoList = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
                    for (ResolveInfo resolveInfo : resInfoList) {
                        String packageName = resolveInfo.activityInfo.packageName;
                        grantUriPermission(packageName, cameraImageUri,
                                Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    }

                    intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraImageUri);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

                } else {
                    // 如果创建URI失败，尝试不使用EXTRA_OUTPUT
                }
                startActivityForResult(intent, REQUEST_CAMERA);
            } catch (Exception e) {
                showNoCameraAppDialog();
            }

        } catch (Exception e) {
            Log.e(TAG, "打开相机失败", e);
            Toast.makeText(this, "无法打开相机: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void openVideoRecorder() {
        try {
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            try {
                // 设置视频质量
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 30);

                startActivityForResult(intent, REQUEST_MEDIA_PICKER);
            } catch (Exception e) {
                showNoVideoRecorderDialog();
            }
        } catch (Exception e) {
            Log.e(TAG, "打开录像机失败", e);
            Toast.makeText(this, "无法打开录像机: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 显示没有相机应用的对话框
     */
    private void showNoCameraAppDialog() {
        new androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle("未找到相机应用")
                .setMessage("您的设备上没有找到可用的相机应用。您可以选择：")
                .setPositiveButton("从应用商店下载", (dialog, which) -> {
                    openAppStoreForCameraApps();
                })
                .setNegativeButton("取消", null)
                .setNeutralButton("使用其他方式", (dialog, which) -> {
                    // 回退到从相册选择
                    openGallery();
                })
                .show();
    }

    /**
     * 显示没有录像应用的对话框
     */
    private void showNoVideoRecorderDialog() {
        new androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle("未找到录像应用")
                .setMessage("您的设备上没有找到可用的录像应用。您可以选择：")
                .setPositiveButton("从应用商店下载", (dialog, which) -> {
                    openAppStoreForCameraApps();
                })
                .setNegativeButton("取消", null)
                .setNeutralButton("使用其他方式", (dialog, which) -> {
                    // 回退到从相册选择视频
                    openGallery();
                })
                .show();
    }

    /**
     * 创建图片URI
     */
    private Uri createImageUri(String fileName) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // Android 10+ 使用 MediaStore
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
            contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);

            return getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        } else {
            // Android 9 及以下使用 FileProvider
            File photoFile = createImageFile(fileName);
            if (photoFile != null) {
                return FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", photoFile);
            }
        }
        return null;
    }

    /**
     * 创建图片文件
     */
    private File createImageFile(String fileName) {
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (storageDir == null) {
            storageDir = getFilesDir();
        }

        try {
            File imageFile = new File(storageDir, fileName);
            if (imageFile.createNewFile()) {
                return imageFile;
            }
        } catch (IOException e) {
            Log.e(TAG, "创建图片文件失败", e);
        }
        return null;
    }

    /**
     * 打开应用商店搜索相机应用
     */
    private void openAppStoreForCameraApps() {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("market://search?q=camera"));
            startActivity(intent);
        } catch (Exception e) {
            // 如果应用商店不可用，打开网页版
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse("https://play.google.com/store/search?q=camera&c=apps"));
                startActivity(intent);
            } catch (Exception ex) {
                Toast.makeText(this, "无法打开应用商店", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void removeMediaFile(String key, int position) {
        for (AttributeConfig attribute : formConfig.getAttributes()) {
            if (attribute.getKey().equals(key) && attribute.getValue() instanceof List) {
                @SuppressWarnings("unchecked")
                List<MediaFile> mediaFiles = (List<MediaFile>) attribute.getValue();
                if (position >= 0 && position < mediaFiles.size()) {
                    mediaFiles.remove(position);
                    adapter.notifyDataSetChanged();
                }
                break;
            }
        }
    }

    private void submitForm() {
        if (validateForm()) {
            Map<String, Object> resultData = collectFormData();
            Intent resultIntent = new Intent();
            resultIntent.putExtra("form_data", (HashMap<String, Object>) resultData);
            setResult(RESULT_OK, resultIntent);
            finish();
        }
    }

    private void cancelForm() {
        setResult(RESULT_CANCELED);
        finish();
    }

    private boolean validateForm() {
        for (AttributeConfig attribute : formConfig.getAttributes()) {
            // 必填项验证
            if (attribute.isRequired() && isEmptyValue(attribute.getValue())) {
                String message = attribute.getTitle() + "是必填项，不能为空";
                Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
                return false;
            }

            // 自定义验证规则验证
            if (attribute.getValue() != null && !isEmptyValue(attribute.getValue())) {
                String value = attribute.getValue().toString();
                String validationRule = attribute.getValidationRule();

                if (validationRule != null && !isValidInput(value, validationRule, attribute)) {
                    String message = attribute.getValidationMessage() != null ?
                            attribute.getValidationMessage() : attribute.getTitle() + "格式不正确";
                    Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
                    return false;
                }

                // 数字范围验证
                if (attribute.getType() == AttributeConfig.AttributeType.NUMBER &&
                        !isEmptyValue(attribute.getValue())) {
                    try {
                        double numValue = Double.parseDouble(value);
                        if (attribute.getMinValue() != 0 && numValue < attribute.getMinValue()) {
                            String message = attribute.getTitle() + "不能小于" + attribute.getMinValue();
                            Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
                            return false;
                        }
                        if (attribute.getMaxValue() != 0 && numValue > attribute.getMaxValue()) {
                            String message = attribute.getTitle() + "不能大于" + attribute.getMaxValue();
                            Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
                            return false;
                        }
                    } catch (NumberFormatException e) {
                        // 忽略，因为前面已经验证过格式
                    }
                }
            }
        }
        return true;
    }

    /**
     * 验证输入值
     */
    private boolean isValidInput(String value, String validationRule, AttributeConfig attribute) {
        switch (validationRule) {
            case "integer":
                return value.matches("-?\\d+");
            case "positive_integer":
                return value.matches("\\d+");
            case "decimal":
                return value.matches("-?\\d+(\\.\\d+)?");
            case "positive_decimal":
                return value.matches("\\d+(\\.\\d+)?");
            case "phone":
                return value.matches("\\d{7,15}");
            case "email":
                return value.matches("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}");
            case "id_card":
                return value.matches("\\d{17}[\\dXx]");
            case "chinese":
                return value.matches("[\\u4e00-\\u9fa5]+");
            case "english":
                return value.matches("[a-zA-Z]+");
            case "no_special_chars":
                return value.matches("[\\w\\u4e00-\\u9fa5]+");
            default:
                return value.matches(validationRule);
        }
    }

    private boolean isEmptyValue(Object value) {
        if (value == null) return true;
        if (value instanceof String) return ((String) value).trim().isEmpty();
        if (value instanceof List) return ((List<?>) value).isEmpty();
        return false;
    }

    private Map<String, Object> collectFormData() {
        Map<String, Object> data = new HashMap<>();
        for (AttributeConfig attribute : formConfig.getAttributes()) {
            data.put(attribute.getKey(), attribute.getValue());
        }
        return data;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_MEDIA_PICKER:
                    handleMediaSelection(data);
                    break;
                case REQUEST_CAMERA:
                    handleCameraResult();
                    break;
                case REQUEST_CUSTOM_CAMERA:
                    handleCustomCameraResult(data);
                    break;
                case REQUEST_CAMERA_X:  // 新增
                    handleCameraXResult(data);
                    break;
            }
        }
    }

    /**
     * 处理 CameraX 相机返回结果
     */
    private void handleCameraXResult(Intent data) {
        if (data != null && data.hasExtra("media_file")) {
            MediaFile mediaFile = (MediaFile) data.getSerializableExtra("media_file");
            if (mediaFile != null) {
                List<MediaFile> mediaFiles = new ArrayList<>();
                mediaFiles.add(mediaFile);
                addMediaFilesToAttribute(mediaFiles);

                // 显示位置信息
//                if (mediaFile.getLocationInfo() != null) {
//                    Toast.makeText(this, "照片已记录位置: " + mediaFile.getLocationInfo().toString(), Toast.LENGTH_LONG).show();
//                }
            }
        }
    }

    /**
     * 处理自定义相机返回结果
     */
    private void handleCustomCameraResult(Intent data) {
        if (data != null && data.hasExtra("media_file")) {
            MediaFile mediaFile = (MediaFile) data.getSerializableExtra("media_file");
            if (mediaFile != null) {
                List<MediaFile> mediaFiles = new ArrayList<>();
                mediaFiles.add(mediaFile);
                addMediaFilesToAttribute(mediaFiles);

                // 显示位置信息
                if (mediaFile.getLocationInfo() != null) {
                    Toast.makeText(this, "照片已记录位置: " + mediaFile.getLocationInfo().toString(), Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    private void handleMediaSelection(Intent data) {
        if (data == null) return;

        List<MediaFile> selectedMediaFiles = new ArrayList<>();

        // 处理单选和多选
        if (data.getClipData() != null) {
            // 多选
            int count = data.getClipData().getItemCount();
            for (int i = 0; i < count; i++) {
                Uri uri = data.getClipData().getItemAt(i).getUri();
                MediaFile mediaFile = createMediaFileFromUri(uri);
                if (mediaFile != null) {
                    selectedMediaFiles.add(mediaFile);
                }
            }
        } else if (data.getData() != null) {
            // 单选
            Uri uri = data.getData();
            MediaFile mediaFile = createMediaFileFromUri(uri);
            if (mediaFile != null) {
                selectedMediaFiles.add(mediaFile);
            }
        } else if (data.getExtras() != null && data.getExtras().get("data") != null) {
            // 从相机返回的缩略图
            // 这里需要保存图片到文件并获取URI
            Toast.makeText(this, "请使用保存到文件的相机应用", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!selectedMediaFiles.isEmpty()) {
            addMediaFilesToAttribute(selectedMediaFiles);
        } else {
            Toast.makeText(this, "未选择有效的媒体文件", Toast.LENGTH_SHORT).show();
        }
    }

    private void handleCameraResult() {
        if (cameraImageUri != null) {
            List<MediaFile> mediaFiles = new ArrayList<>();
            MediaFile mediaFile = new MediaFile(cameraImageUri.toString(), MediaFile.MediaType.IMAGE);
            mediaFile.setName("d_" + System.currentTimeMillis());

            // 如果是从带位置拍照过来的，添加位置信息
            if (currentAction.equals("camera_with_location") && currentLocationInfo != null) {
                mediaFile.setLocationInfo(currentLocationInfo);
            }

            mediaFiles.add(mediaFile);
            addMediaFilesToAttribute(mediaFiles);

            // 清理临时位置信息
            currentLocationInfo = null;
        }
    }

    private MediaFile createMediaFileFromUri(Uri uri) {
        try {
            String filePath = getFilePathFromUri(uri);
            if (filePath == null) {
                // 如果无法获取文件路径，使用URI
                filePath = uri.toString();
            }

            String mimeType = getContentResolver().getType(uri);
            MediaFile.MediaType mediaType = isVideoMimeType(mimeType) ?
                    MediaFile.MediaType.VIDEO : MediaFile.MediaType.IMAGE;

            MediaFile mediaFile = new MediaFile(filePath, mediaType);
            mediaFile.setName(getFileNameFromUri(uri));

            // 如果是视频，生成缩略图路径（实际项目中可能需要生成缩略图）
            if (mediaType == MediaFile.MediaType.VIDEO) {
                mediaFile.setThumbnail(filePath); // 实际项目中应该生成真正的缩略图
            }

            return mediaFile;
        } catch (Exception e) {
            Log.e(TAG, "创建媒体文件失败", e);
            return null;
        }
    }

    private String getFilePathFromUri(Uri uri) {
        if (uri == null) return null;

        String scheme = uri.getScheme();
        if (scheme == null || scheme.equals("file")) {
            return uri.getPath();
        } else if (scheme.equals("content")) {
            String[] projection = {MediaStore.Images.Media.DATA};
            try (Cursor cursor = getContentResolver().query(uri, projection, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    return cursor.getString(columnIndex);
                }
            } catch (Exception e) {
                Log.e(TAG, "获取文件路径失败", e);
            }
        }
        return null;
    }

    private String getFileNameFromUri(Uri uri) {
        if (uri == null) return "未知文件";

        String result = null;
        if (uri.getScheme().equals("content")) {
            try (Cursor cursor = getContentResolver().query(uri, null, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    int nameIndex = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME);
                    if (nameIndex != -1) {
                        result = cursor.getString(nameIndex);
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "获取文件名失败", e);
            }
        }

        if (result == null) {
            result = uri.getPath();
            if (result != null) {
                int cut = result.lastIndexOf('/');
                if (cut != -1) {
                    result = result.substring(cut + 1);
                }
            }
        }

        return result != null ? result : "未知文件";
    }

    private boolean isVideoMimeType(String mimeType) {
        return mimeType != null && mimeType.startsWith("video/");
    }

    @SuppressWarnings("unchecked")
    private void addMediaFilesToAttribute(List<MediaFile> newMediaFiles) {
        if (currentMediaKey == null) return;

        for (AttributeConfig attribute : formConfig.getAttributes()) {
            if (attribute.getKey().equals(currentMediaKey)) {
                List<MediaFile> existingMediaFiles = attribute.getValue() instanceof List ?
                        (List<MediaFile>) attribute.getValue() : new ArrayList<>();

                existingMediaFiles.addAll(newMediaFiles);
                attribute.setValue(existingMediaFiles);
                adapter.notifyDataSetChanged();
                break;
            }
        }
    }

    @Override
    public boolean onSupportNavigateUp() {
        cancelForm();
        return true;
    }
}